package cn.lyjuan.first.netty._4_netty_serialize.server;

import cn.lyjuan.first.netty._4_netty_serialize.msg.MyMessage;
import cn.lyjuan.first.netty._4_netty_serialize.msg.reader.impl.HelloReaderImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.InetSocketAddress;

public class ServerHandler extends SimpleChannelInboundHandler<MyMessage>
{
    private static Logger log = LogManager.getLogger(ServerHandler.class);

    private HelloReaderImpl helloWriter;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyMessage msg) throws Exception
    {
        InetSocketAddress host = (InetSocketAddress) ctx.channel().remoteAddress();
        String addr = host.getHostName() + ":" + host.getPort();
        log.info("server receive from " + addr + ": " + msg);

        // 回写
        msg = helloWriter.write();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        InetSocketAddress host = (InetSocketAddress) ctx.channel().remoteAddress();
        log.debug("Active: " + host.getHostName() + ":" + host.getPort());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception
    {
        InetSocketAddress host = (InetSocketAddress) ctx.channel().remoteAddress();
        log.debug("Inactive: " + host.getHostName() + ":" + host.getPort());
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        // 关闭通道
        try
        {
            ctx.channel().close();
        } catch (Throwable t)
        {
            // todo 异常处理
            t.printStackTrace();
        }

        super.exceptionCaught(ctx, cause);
    }

    public HelloReaderImpl getHelloWriter()
    {
        return helloWriter;
    }

    public ServerHandler setHelloWriter(HelloReaderImpl helloWriter)
    {
        this.helloWriter = helloWriter;
        return this;
    }
}
